package cn.tjad.tjad2.module.document.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.qiandian.android.base.activity.BaseActivity;
import com.qiandian.android.base.common.bean.BaseBean;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.common.bean.CommonListBean;
import com.qiandian.android.base.net.http.HttpConstants;
import com.qiandian.android.base.net.http.HttpId;
import com.qiandian.android.base.net.http.IDataCallBack;
import com.qiandian.android.base.widget.TJADTTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.business.RemoteDataService;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.FileBean;
import cn.tjad.tjad2.data.bean.Link;
import cn.tjad.tjad2.data.event.DocLinkDeleteEvent;
import cn.tjad.tjad2.module.document.adapter.DocLinkListAdapter;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.Tools;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;

@Route(path = PageId.DOC_LINK)
public class DocLinkActivity extends BaseActivity implements IDataCallBack {

    @BindView(R.id.doc_name)
    TextView docNameTV;
    @BindView(R.id.doc_link_list)
    RecyclerView docLinkList;
    private DocLinkListAdapter adapter;

    private FileBean fileBean;
    private int projectId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.doc_link_setting_layout);
        EventBus.getDefault().register(this);
        projectId = TjadApplication.getInstance().getSession().getProjectId();
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        docLinkList.setLayoutManager(layoutManager);
        docLinkList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        adapter = new DocLinkListAdapter(null);
        docLinkList.setAdapter(adapter);
        handleIntent(getIntent());
    }

    private void handleIntent(Intent intent) {
        if (intent == null) {
            return;
        }
        fileBean = (FileBean) intent.getSerializableExtra(Keys.FILE);
        if (fileBean != null) {
            docNameTV.setText(fileBean.name);
            if (fileBean.document == null) {
                Tools.showToast("该文件缺少document参数");
                finish();
            }
        } else {
            Tools.showToast("参数不正确");
            finish();
        }
        requestFileLinks();
    }

    @Override
    protected void setCustomerTitle(TJADTTitleView titleView) {
        super.setCustomerTitle(titleView);
        titleView.showRight(true);
        titleView.setRightText("新建链接");
    }

    @Override
    public void onTitleClick(int which) {
        super.onTitleClick(which);
        switch (which) {
            case TJADTTitleView.TITLE_RIGHT:
                gotoAddNewLink();
                break;
        }
    }

    private void requestFileLinks() {
        int projectId = TjadApplication.getInstance().getSession().getProjectId();
        int docId = fileBean.document.id;
        RemoteDataService.getDocLink(projectId, docId, this);
    }

    private void gotoAddNewLink() {
        Bundle bundle = new Bundle();
        bundle.putSerializable(Keys.FILE, fileBean);
        RouteUtils.toPageForResult(this, PageId.FILE_SELECT, bundle, 1001);
    }

    @Override
    public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
        if (httpId == HttpId.DOC_LINK) {
            Tools.showToast(errorMsg);
        } else if (httpId == HttpId.ADD_DOC_LINK || httpId == HttpId.DELETE_DOC_LINK) {
            if (TextUtils.isEmpty(errorMsg)) {
                TjDialogFragment.Builder builder = new TjDialogFragment.Builder(this);
                builder.setTitle("提示")
                        .setMessage(errorMsg)
                        .setNegativeButton("确定", null)
                        .show(getSupportFragmentManager());
            }
        }
        return false;
    }

    @Override
    public void onDataRefresh(int httpId, Object responseBean) {
        if (httpId == HttpId.DOC_LINK) {
            CommonListBean<Link> bean = (CommonListBean<Link>) responseBean;
            if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                onDocLinkGet(bean.result);
            } else {
                Tools.showToast(bean.respMsg);
            }
        } else if (httpId == HttpId.ADD_DOC_LINK) {
            CommonBean<BaseBean> bean = (CommonBean<BaseBean>) responseBean;
            if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                requestFileLinks();
                TjDialogFragment.Builder builder = new TjDialogFragment.Builder(this);
                builder.setTitle("提示")
                        .setMessage("链接设置成功！")
                        .setNegativeButton("确定", null)
                        .show(getSupportFragmentManager());
            } else {
                if (TextUtils.isEmpty(bean.respMsg)) {
                    TjDialogFragment.Builder builder = new TjDialogFragment.Builder(this);
                    builder.setTitle("提示")
                            .setMessage(bean.respMsg)
                            .setNegativeButton("确定", null)
                            .show(getSupportFragmentManager());
                }
            }
        } else if (httpId == HttpId.DELETE_DOC_LINK) {
            CommonBean<BaseBean> bean = (CommonBean<BaseBean>) responseBean;
            if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                requestFileLinks();
                TjDialogFragment.Builder builder = new TjDialogFragment.Builder(this);
                builder.setTitle("提示")
                        .setMessage("链接删除成功！")
                        .setNegativeButton("确定", null)
                        .show(getSupportFragmentManager());
            } else {
                if (TextUtils.isEmpty(bean.respMsg)) {
                    TjDialogFragment.Builder builder = new TjDialogFragment.Builder(this);
                    builder.setTitle("提示")
                            .setMessage(bean.respMsg)
                            .setNegativeButton("确定", null)
                            .show(getSupportFragmentManager());
                }
            }
        }
    }

    private void onDocLinkGet(List<Link> result) {
        adapter.updateData(result);
        adapter.notifyDataSetChanged();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1001) {
            if (resultCode == RESULT_OK) {
                FileBean selectFile = (FileBean) data.getSerializableExtra(Keys.FILE);
                if (selectFile != null) {
                    addLinkTo(selectFile);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void addLinkTo(final FileBean linkFile) {
        TjDialogFragment.Builder builder = new TjDialogFragment.Builder(this);
        builder.setTitle("设置链接")
                .setMessage("是否将文件链接到\"" + linkFile.name + "\"？")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", new OnDialogClickListener() {
                    @Override
                    public boolean onClick(Dialog dialogInterface, int i) {
                        RemoteDataService.addDocLink(projectId, fileBean.document.id, linkFile.id, DocLinkActivity.this);
                        return true;
                    }
                })
                .show(getSupportFragmentManager());

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deleteLink(DocLinkDeleteEvent event) {
        final Link link = event.getLinkBean();
        TjDialogFragment.Builder builder = new TjDialogFragment.Builder(this);
        builder.setTitle("删除链接链接")
                .setMessage("是否删除链接\"" + link.name + "\"？")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", new OnDialogClickListener() {
                    @Override
                    public boolean onClick(Dialog dialogInterface, int i) {
                        RemoteDataService.deleteDocLink(projectId, fileBean.document.id, link.id, DocLinkActivity.this);
                        return true;
                    }
                })
                .show(getSupportFragmentManager());
    }
}
